package com.xzq.register;

import com.alibaba.fastjson.JSONObject;
import com.xzq.pojo.ProviderService;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.CollectionUtils;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/22 22:50
 * @Version 1.0.0
 **/
public class RedisRegister implements Register , InitializingBean, DisposableBean {
    private static final String PREFIX = "RPC:SERVERS:";
    private static final List<String> registerServices = new ArrayList<>();
    private String host;
    private Integer port;
    private String auth;

    public RedisRegister(String host, Integer port,String auth) {
        this.host = host;
        this.port = port;
        this.auth = auth;
    }


    private Jedis jedis;

    @Override
    public void register(ProviderService providerService) {
        String key = PREFIX + providerService.getServiceName();
        registerServices.add(key);
        jedis.lpush(key, JSONObject.toJSONString(providerService));
    }



    @Override
    public ProviderService findService(String serviceName) {
        List<String> services = jedis.lrange(PREFIX + serviceName, 0, -1);
        if (!CollectionUtils.isEmpty(services)) {
            return JSONObject.parseObject(services.get(0), ProviderService.class);
        }
        return null;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        jedis = new Jedis(host, port);
        jedis.auth(auth);
    }

    @Override
    public void destroy() throws Exception {
        String[] array = registerServices.toArray(new String[0]);
        jedis.del(array);
    }
}
